package com.ruoyi.agent.controller;

import java.time.LocalDateTime;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.agent.domain.SysAgentListVO;
import com.ruoyi.agent.domain.SysAgentStatusDTO;
import com.ruoyi.agent.domain.SysInterfacePrice;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.agent.mapper.SysInterfacePriceMapper;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.ISysRoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.service.ISysAgentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 管理Controller
 *
 * @author ruoyi
 * @date 2024-06-12
 */
@RestController
@RequestMapping("/agent/agentManage")
public class SysAgentController extends BaseController
{
    @Autowired
    private ISysAgentService sysAgentService;

    @Autowired
    private SysInterfacePriceMapper interfacePriceMapper;

    @Autowired
    private SysAgentMapper agentMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 查询管理列表
     */
    @PreAuthorize("@ss.hasPermi('agent:agentManage:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysAgent sysAgent)
    {

        Long deptId = SecurityUtils.getDeptId();
        if (!deptId.equals(100l)) {
            throw new ServiceException("您没有权限查看代理商信息");
        }
        startPage();
        List<SysAgent> list = sysAgentService.selectSysAgentList(sysAgent);


        return getDataTable(list);
    }

    /**
     * 导出管理列表
     */
    @PreAuthorize("@ss.hasPermi('agent:agentManage:export')")
    @Log(title = "管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysAgent sysAgent)
    {
        List<SysAgent> list = sysAgentService.selectSysAgentList(sysAgent);
        ExcelUtil<SysAgent> util = new ExcelUtil<SysAgent>(SysAgent.class);
        util.exportExcel(response, list, "管理数据");
    }

    /**
     * 获取管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('agent:agentManage:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysAgentService.selectSysAgentById(id));
    }

    /**
     * 新增管理
     */
    @PreAuthorize("@ss.hasPermi('agent:agentManage:add')")
    @Log(title = "管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAgent sysAgent)
    {
        return success(sysAgentService.insertSysAgent(sysAgent));
    }

    /**
     * 修改管理
     */
    @PreAuthorize("@ss.hasPermi('agent:agentManage:edit')")
    @Log(title = "管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAgent sysAgent)
    {
        return toAjax(sysAgentService.updateSysAgent(sysAgent));
    }

    /**
     * 删除管理
     */
    @PreAuthorize("@ss.hasPermi('agent:agentManage:remove')")
    @Log(title = "管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysAgentService.deleteSysAgentByIds(ids));
    }


    @PostMapping("/addInterfacePrice")
    public AjaxResult addInterfacePrice(@RequestBody @Validated SysInterfacePrice interfacePrice) {

        //查询对应的agentId是否存在
        SysAgent sysAgent = sysAgentService.selectSysAgentById(interfacePrice.getAgentId());
        if (sysAgent==null) {
            throw new ServiceException("当前代理商不存在，请返回重试");
        }

        //删除对应的agent价格表
       List<SysInterfacePrice> interfacePrices= interfacePriceMapper.selectByAgentId(interfacePrice.getAgentId());

        if (!CollectionUtils.isEmpty(interfacePrices)) {
            //删除对应的数据
            interfacePriceMapper.deleteByAgentId(interfacePrice.getAgentId());
        }

        interfacePrice.setCreateTime(LocalDateTime.now()).setCreateBy(SecurityUtils.getUsername());
        //插入新的数据到表
        interfacePriceMapper.insertSysInterfacePrice(interfacePrice);


        return success();


    }


    //接口回显
    @PostMapping("/getInterfacePrice/{agentId}")
    public AjaxResult getInterfacePrice(@PathVariable("agentId") Long agentId) {
        List<SysInterfacePrice> interfacePrices = interfacePriceMapper.selectByAgentId(agentId);
        if (interfacePrices.size()>1) {
            //删除里面的所有
            interfacePriceMapper.deleteByAgentId(agentId);
        }
        SysInterfacePrice sysInterfacePrice = interfacePrices.get(0);
        return success(sysInterfacePrice);

    }

    //修改对应的接口信息
    @PostMapping("/resetInterfacePrice")
    public AjaxResult resetInterfacePrice(@RequestBody @Validated SysInterfacePrice interfacePrice) {
        //判断当前用户是否为管理端用户

        if (!SecurityUtils.getDeptId().equals(100l)) {
            throw new ServiceException("您没有权限操作");
        }


        //当前代理商是否存在
        SysAgent sysAgent = sysAgentService.selectSysAgentById(interfacePrice.getAgentId());
        if (sysAgent==null) {
            throw new ServiceException("代理商不存在");
        }

        interfacePrice.setCreateTime(LocalDateTime.now()).setCreateBy(SecurityUtils.getUsername());
        //当前价格表是否存在
        List<SysInterfacePrice> interfacePrices = interfacePriceMapper.selectByAgentId(interfacePrice.getAgentId());
        if (CollectionUtils.isEmpty(interfacePrices)) {
            //插入新的数据到表
            interfacePriceMapper.insertSysInterfacePrice(interfacePrice);

        }
        else {
            // 存在修改
            interfacePriceMapper.updateByAgentId(interfacePrice);
        }


        return success();


    }



    //查询所有代理商
    @PostMapping("/listAllAgent")
    public AjaxResult listAllAgent() {
        //判断当前用户是否有该权限

        Long deptId = SecurityUtils.getDeptId();
        if (!deptId.equals(100l)) {
            throw new ServiceException("该用户并没有该权限");
        }


        List<SysAgentListVO> agentListVOS= agentMapper.selectAllSysAgentIdAndName();
       return success(agentListVOS);
    }


    /**
     *
     * 启用 禁用代理商用户
     *
     */

    @PostMapping("/resetStatus")
    public AjaxResult UpOrNoAgentStatus(@RequestBody SysAgentStatusDTO statusDTO) {

        sysAgentService.UpOrNoAgentStatus(statusDTO);

        return success("修改成功");

    }



    //代理商后台权限回显
    @PostMapping("/listAgentAuthorized/{agentId}")
    public AjaxResult listAgentAuthorized(@PathVariable("agentId") Long agentId) {

        Long deptId = SecurityUtils.getDeptId();
        if (!deptId.equals(100l)) {
            throw new ServiceException("您没有权限操作");
        }


        //根据agentId查询到对应agent，获取到对应得用户id和部门id，根据查找对应得第一个角色
        SysAgent sysAgent = agentMapper.selectSysAgentById(agentId);
        if (sysAgent==null) {
            throw new ServiceException("代理商异常");
        }

        Long userId = sysAgent.getUserId();



        List<Long>  roles =  roleMapper.selectRoleIdsByUserId(userId);
       if (CollectionUtils.isEmpty(roles) || roles.size()<=0) {
           throw new ServiceException("当前代理商异常");
       }

        Long sysRoleId = roles.get(0);

        SysRole sysRole = roleService.selectRoleById(sysRoleId);

        return success(sysRole);

    }


    //修改后台权限
    @PostMapping("/resetAgentAuthorized/{agentId}")
    public AjaxResult resetAgentAuthorized(@PathVariable("agentId") Long agentId) {

        Long deptId = SecurityUtils.getDeptId();
        if (!deptId.equals(100l)) {
            throw new ServiceException("您没有权限操作");
        }


        //根据agentId查询到对应agent，获取到对应得用户id和部门id，根据查找对应得第一个角色
        SysAgent sysAgent = agentMapper.selectSysAgentById(agentId);
        if (sysAgent==null) {
            throw new ServiceException("代理商异常");
        }

        Long userId = sysAgent.getUserId();


        List<Long>  roles = roleMapper.selectRoleListByUserId(userId);

        if (CollectionUtils.isEmpty(roles) || roles.size()<=0) {
            throw new ServiceException("当前代理商异常");
        }

        Long sysRoleId = roles.get(0);

        SysRole sysRole = roleService.selectRoleById(sysRoleId);

        return success(sysRole);

    }

}
